package zhexian.app.smartcall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;

public class SelectPicActivity extends Activity implements OnClickListener {

    /***
     * 使用照相机拍照获取图片
     */
    public static final int SELECT_PIC_BY_TAKE_PHOTO = 1;
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;

    /***
     * 从Intent获取图片路径的KEY
     */
    public static final String KEY_PHOTO_URI = "photo_uri";

    private static final String TAG = "SelectPicActivity";
//    private static final String TMP_AVATAR_DIR = "MyAvatar";
//    private static final String AVATAR_FILE = "com.syw.avatar.jpg";

    private Intent lastIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_pic_layout);
        initView();
    }

    /**
     * 初始化加载View
     */
    private void initView() {
        LinearLayout dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);
        dialogLayout.setOnClickListener(this);
        Button takePhotoBtn = (Button) findViewById(R.id.btn_takePhoto);
        takePhotoBtn.setOnClickListener(this);
        Button pickPhotoBtn = (Button) findViewById(R.id.btn_pick_photo);
        pickPhotoBtn.setOnClickListener(this);
        Button cancelBtn = (Button) findViewById(R.id.btn_cancel);
        cancelBtn.setOnClickListener(this);

        lastIntent = getIntent();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dialog_layout:
                finish();
                break;
            case R.id.btn_takePhoto:
                takePhoto();
                break;
            case R.id.btn_pick_photo:
                pickPhoto();
                break;
            default:
                finish();
                break;
        }
    }

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        //执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
            startActivityForResult(intent, SELECT_PIC_BY_TAKE_PHOTO);
        } else {
            Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
        }
    }

    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return super.onTouchEvent(event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
//	private void doPhoto(int requestCode,Intent data)
//	{
//		if(requestCode == SELECT_PIC_BY_PICK_PHOTO )  //从相册取图片，有些手机有异常情况，请注意
//		{
//			if(data == null)
//			{
//				Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
//				return;
//			}
//			photoUri = data.getData();
//			if(photoUri == null )
//			{
//				Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
//				return;
//			}
//		}
//		String[] pojo = {MediaStore.Images.Media.DATA};
//		Cursor cursor = managedQuery(photoUri, pojo, null, null,null);
//		if(cursor != null )
//		{
//			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
//			cursor.moveToFirst();
//			picPath = cursor.getString(columnIndex);
//			cursor.close();
//		}
//		Log.i(TAG, "imagePath = " + picPath);
//		if(picPath != null && ( picPath.endsWith(".png") || picPath.endsWith(".PNG") ||picPath.endsWith(".jpg") ||picPath.endsWith(".JPG")  ))
//		{
//			lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
//			setResult(Activity.RESULT_OK, lastIntent);
//			finish();
//		}else{
//			Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
//		}
//	}
    private void doPhoto(int requestCode, Intent data) {
        Uri photoUri = null;

        if (requestCode == SELECT_PIC_BY_TAKE_PHOTO) {
            final File file = getTempFile(this);
            photoUri = Uri.fromFile(file);
            finishByUri(photoUri);
            return;
        } else {
            if(data != null) {
                photoUri = data.getData();
            }

            if (photoUri != null) {
                finishByUri(photoUri);
            } else {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                setResult(RESULT_CANCELED);
                finish();
            }
        }

    }

    private void finishByUri(Uri photoUri) {
        lastIntent.putExtra(KEY_PHOTO_URI, photoUri);
        setResult(Activity.RESULT_OK, lastIntent);
        finish();
    }

    private File getTempFile(Context context){
        //it will return /sdcard/image.tmp
        final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
        if(!path.exists()){
            path.mkdir();
        }
        return new File(path, "image.tmp");
    }

//    public static boolean saveImage(Bitmap photo, String spath) {
//        try {
//            BufferedOutputStream bos = new BufferedOutputStream(
//                    new FileOutputStream(spath, false));
//            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//            bos.flush();
//            bos.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//        return true;
//    }
//
//    private String getRealPathFromURI(Uri contentUri) {
//        String[] projx = { MediaStore.Images.Media.DATA };
//        Cursor cursor = managedQuery(contentUri, projx, null, null, null);
//        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//        cursor.moveToFirst();
//        return cursor.getString(column_index);
//    }
}
